/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.util;
import java.io.ByteArrayOutputStream;


public class Str2Hex {
	private static String hexString = "0123456789ABCDEF";
	
	public static void main(String[] args){
		String sStr = GetEncodeStr("UTF-8");
		
		sStr = GetDecodeStr(sStr);
	}

	public static String GetEncodeStr(String str) {
	
		byte[] bytes = null;
		try {
			bytes = str.getBytes("UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		
		for (int i = 0; i < bytes.length; i++) {
			sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
			sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
		}
		return sb.toString();
	}

	public static String GetDecodeStr(String bytes){
		String sRes = "";
		ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length()/2);
		
		for(int i=0;i<bytes.length();i+=2)
		baos.write((hexString.indexOf(bytes.charAt(i))<<4 |hexString.indexOf(bytes.charAt(i+1))));
		
		try {
			sRes = new String(baos.toByteArray(),"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sRes;
	}
}
